package com.moc.controller;

import com.moc.utils.AesUtils;
import com.moc.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 模拟Sass
 *
 * @author XuJiangbo
 */
@Api(tags = {"Sass平台"})
@Slf4j
@RestController
@RequestMapping("/sass")
public class SassMockController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    @ApiOperation(value = "业务数据接口")
    public Result addRecord() {
        //确定主要参数
        String appId = "appId";
        String appSecret = "123";
        String tenantId = "tenantId";
        long timeStamp = System.currentTimeMillis();
        String addUrl = "http://localhost:8087/producer/add";//接口地址
        String reduceUrl = "http://localhost:8087/producer/reduce";

        //造数据
        ArrayList<Object> list = new ArrayList<>();
        HashMap<String, Object> dataMap1 = new HashMap<>();
        HashMap<String, Object> dataMap2 = new HashMap<>();
        dataMap1.put("userId", "1");
        dataMap1.put("monetary", 10);
        dataMap2.put("userId", "2");
        dataMap2.put("monetary", 20);
        list.add(dataMap1);
        list.add(dataMap2);


        //加密
        HashMap<String, Object> signMap = new HashMap<>();
        signMap.put("appId", appId);
        signMap.put("tenantId", tenantId);
        signMap.put("timeStamp", timeStamp);
        signMap.put("data", list);

        String signature = null;
        try {
            signature = AesUtils.getSignature(signMap, appSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String enData = null;
        try {
            enData = AesUtils.getEncryptedData(list, appSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        signMap.put("signature", signature);
        signMap.put("data", enData);

        //发送数据
        HttpHeaders headers = new HttpHeaders();
        //设置请求行参数application/json
        headers.setContentType(MediaType.APPLICATION_JSON);
        ResponseEntity<Result> userResponseEntity = restTemplate.postForEntity(addUrl, signMap, Result.class);
        if (userResponseEntity == null) {
            System.out.println("网络异常，请稍后再试");
            return null;
        }

        //接收发送结果
        Result result = userResponseEntity.getBody();
        return result;
    }
}
